package models

import (
	"github.com/jinzhu/gorm"
	"kop/modules/building/configuration"
	"kop/modules/building/entity"
	"kop/pb"
)

func AutoMigrate(dB *gorm.DB) {

	dB.AutoMigrate(new(entity.Building))
}

func GetBuildings(dB *gorm.DB, roleID int32) []*pb.Building {

	var buildings []*pb.Building
	var data []entity.Building
	if err := dB.Where("role_id = ?", roleID).Find(&data).Error; err != nil {
		panic(err)
	}

	if len(data) == 0 {

		var buildingAttrConf = configuration.GetByBuildingID(entity.HALL).GetAttrByLevel(1)

		var hall = Create(dB, roleID, entity.HALL, buildingAttrConf.MoneyIncome)
		buildings = append(buildings, hall)

	} else {

		for _, b := range data {

			buildings = append(buildings, buildPbBuilding(b))
		}
	}

	return buildings
}

// 解锁新建筑
// coin: 计算好的建筑收益
func Create(dB *gorm.DB, roleID, buildingID int32, coin int64) *pb.Building {

	var b = entity.Building{
		RoleID:     roleID,
		BuildingID: buildingID,
		Level:      1,
		Coin:       coin,
	}

	if err := dB.Create(&b).Error; err != nil {
		panic(err)
	}

	return buildPbBuilding(b)
}

func GetByBuildingID(dB *gorm.DB, roleID, buildingID int32) (*pb.Building, bool) {

	var b = entity.Building{
		RoleID:     roleID,
		BuildingID: buildingID,
	}

	if err := dB.First(&b).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			panic(err)
		}

		return nil, false
	}

	return buildPbBuilding(b), true
}

func SaveBuilding(dB *gorm.DB, building *pb.Building) {

	var b = entity.Building{
		RoleID:     building.RoleID,
		BuildingID: building.BuildingID,
		Level:      building.Level,
		Seaman:     building.Seaman,
		Coin:       building.Coin,
		Captain1:   building.Captain1,
		Captain2:   building.Captain2,
		Captain3:   building.Captain3,
		Captain4:   building.Captain4,
		Captain5:   building.Captain5,
	}

	if err := dB.Save(&b).Error; err != nil {
		panic(err)
	}

	*building = *buildPbBuilding(b)
}

func Income(dB *gorm.DB, roleID int32) (int64, error) {

	var building entity.Building
	var res = struct {
		S int64
	}{}

	return res.S, dB.Table(building.TableName()).Select("SUM(coin) AS S").Where("role_id = ? AND building_id != ?", roleID, entity.HALL).First(&res).Error
}

func buildPbBuilding(b entity.Building) *pb.Building {

	var building = pb.Building{
		RoleID:     b.RoleID,
		BuildingID: b.BuildingID,
		Level:      b.Level,
		Seaman:     b.Seaman,
		Coin:       b.Coin,
		Captain1:   b.Captain1,
		Captain2:   b.Captain2,
		Captain3:   b.Captain3,
		Captain4:   b.Captain4,
		Captain5:   b.Captain5,
	}

	var buildingAttrConf = configuration.GetByBuildingID(building.BuildingID).GetAttrByLevel(building.Level)

	building.ItemCost = buildingAttrConf.ItemCost
	building.MoneyCost = buildingAttrConf.MoneyCost
	building.SailorCost = buildingAttrConf.SailorCost

	return &building
}
